package com.learn.mybatis.model;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author wangxing
 * @date 2020/4/28.
 */
public class Model {

    @Override
    public String toString() {
        Field[] arr_f = this.getClass().getDeclaredFields();
        StringBuilder str = new StringBuilder("Model{");
        String column_name;
        String val;
        String column_type;
        for (Field f : arr_f) {
            column_name = f.getName();
            column_type = f.getGenericType().toString();
            val = this.getObjColumnValue(this, column_name, column_type);
            str.append(column_name)
                    .append(":")
                    .append(val)
                    .append(" ");

        }
        str.append("}");
        return str.toString();
    }

    /**
     * 获取对象的属性值
     *
     * @param obj         对象
     * @param column_name 属性名
     * @param column_type 属性类型
     * @return
     */
    private String getObjColumnValue(Object obj, String column_name, String column_type) {
        Method m;
        String val = null;
        try {
            m = (Method) obj.getClass().getMethod("get" + column_name.substring(0, 1).toUpperCase() + column_name.substring(1));
            Object t = m.invoke(obj);
            if (column_type.indexOf("String") != -1) {
                val = (String) m.invoke(obj);
            } else if (column_type.indexOf("String") == -1) {
                val = String.valueOf(m.invoke(obj));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return val;
    }
}
